<?php
namespace Robot\Controller;
use Common\Controller\RobotController;
define("TOKEN", "yuanyitoken");
class IdiomController extends RobotController {

    public function check_server(){     //校验服务器地址URL
        if (isset($_GET['echostr'])) {
            $this->valid();
        }else{
            $this->responsexml();
        }
    }

    private function valid()
    {
        $echoStr = $_GET["echostr"];
        if($this->checkSignature()){
            header('content-type:text');
            echo $echoStr;
            exit;
        }else{
            echo $echoStr.'+++'.TOKEN;
            exit;
        }
    }

    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }


    public function responsexml(){

        include_once "WXBizMsgCrypt.php";

        $token = TOKEN;
        $encodingAesKey = "LTDUQSVALfdPOsSjNEYJvByIMZo1UVLp7iC0rOIJour";
        $appId = "wx71e7a983a194c512";

       $encryptMsg = file_get_contents('php://input');


        $pc = new \WXBizMsgCrypt($token, $encodingAesKey, $appId);

        $timeStamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $msg_sign   = $_GET['msg_signature'];

        $xml_tree = new \DOMDocument();
        $xml_tree->loadXML($encryptMsg);
        $array_e = $xml_tree->getElementsByTagName('Encrypt');

        $encrypt = $array_e->item(0)->nodeValue;

        $format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
        $from_xml = sprintf($format, $encrypt);

        $msg = '';

        $errCode = $pc->decryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg);



        if ($errCode == 0) {

            $xml = new \DOMDocument();

            $xml->loadXML($msg);

            $array1 = $xml->getElementsByTagName('ToUserName');
            $array2 = $xml->getElementsByTagName('FromUserName');
            $array3 = $xml->getElementsByTagName('MsgType');
            $array4 = $xml->getElementsByTagName('Content');
            $array5 = $xml->getElementsByTagName('CreateTime');
            $array6 = $xml->getElementsByTagName('MsgId');

            $ToUserName = $array1->item(0)->nodeValue;

            $FromUserName = $array2->item(0)->nodeValue;
            $MsgType = $array3->item(0)->nodeValue;
            $CreateTime = $array5->item(0)->nodeValue;
            $Content = $array4->item(0)->nodeValue;

            $MsgId = $array6->item(0)->nodeValue;

            $Content = trim($Content);
//          $postObj = simplexml_load_string($msg, 'SimpleXMLElement', LIBXML_NOCDATA);


            if ($MsgType=='text'){

                $insert = array(
                    'openid'=>$FromUserName,
                    'gid'=>$ToUserName,
                    'msgtype'=>$MsgType,
                    'content'=>$Content,
                    'createtime'=>date('Y-m-d H:i:s',$CreateTime),
                    'msgid'=>$MsgId
                );
                M('idiom_msg')->data($insert)->add();
            }


            $time = time();


            $sendtext = '游戏规则： 
  1.  完成挑战即可获得随机红包 
  2.  累计金额达到5元可以发起提现 
  3.  每日有一次免费挑战机会';

            $msgtype = "text";

            $appid = "wx71e7a983a194c512";
            $secret = "5b4e4315c5064fe780f46cbde2ed6ba6";
            $access_token = $this->gettoken($appid,$secret);

            $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=$access_token";

            $data = array(
                'touser'=>$FromUserName,
                'msgtype'=>$msgtype,
                'text'=>array(
                    'content'=>$sendtext,
                )
            );

            $sendtext2 =
                '关于奖金发放
 1.  提现请添加工作人员微信ONETECHCLUB，工作人员将定时为您发放红包奖励。
 2.  放假期间回复可能有延误，我们工作人员看到消息会第一时间为您发放红包，请见谅！
 3.  有其他咨询事宜，请添加我们工作人员微信。微信号：ONETECHCLUB';

            $data2 = array(
                'touser'=>$FromUserName,
                'msgtype'=>$msgtype,
                'text'=>array(
                    'content'=>$sendtext2,
                )
            );

            $sendtext3 = "重要事情再重复一遍：领奖请添加工作人员微信号：ONETECHCLUB";

            $data3 = array(
                'touser'=>$FromUserName,
                'msgtype'=>$msgtype,
                'text'=>array(
                    'content'=>$sendtext3,
                )
            );
            $json3 = json_encode($data3,JSON_UNESCAPED_UNICODE);

            $json2 = json_encode($data2,JSON_UNESCAPED_UNICODE);

            $json = json_encode($data,JSON_UNESCAPED_UNICODE);

            $res = $this->getcomponent($url,$json);

            $this->getcomponent($url,$json2);
            $this->getcomponent($url,$json3);
            echo 'success';exit;


//            $send = "<xml>
//    <ToUserName><![CDATA[$FromUserName]]></ToUserName>
//    <FromUserName><![CDATA[$ToUserName]]></FromUserName>
//    <CreateTime>$time</CreateTime>
//    <MsgType><![CDATA[$msgtype]]></MsgType>
//    <Content><![CDATA[$sendtext]]></Content>
//    <FuncFlag><![CDATA[0]]></FuncFlag>
//</xml>";

        }
    }


}